package com.damon.exception;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.damon.common.ResultModel;


/**
 * 拦截异常后返回json信息，如果需要返回html页面，需要通过ModelAndView返回
 * @author
 *
 */
@RestControllerAdvice
public class JsonResultExceptionHandler {
	
	
	private static final Logger logger = LoggerFactory.getLogger(JsonResultExceptionHandler.class);

	
	/**
	 * 前端提示信息
	 * @param req
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler(value = CustomPromptException.class)
	public ResultModel promptMessageHandler(HttpServletRequest req, 
			Exception e) throws Exception {
//		e.printStackTrace();
		CustomPromptException customPE = (CustomPromptException) e;
		
		logger.error("自定义异常响应信息："+ResultModel.errorMsg(customPE.getMessage()).toString()+"\n");
		return ResultModel.errorMsg(customPE.getMessage());
		
	}
	/**
	 * ps：拦截所有未被try-catch的Excepion子类异常
	 * @param req
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler(value = Exception.class)
	public ResultModel defaultErrorHandler(HttpServletRequest req, 
			Exception e) throws Exception {
		e.printStackTrace();
		if(e instanceof HttpMessageNotReadableException) {
			logger.error("异常响应信息："+ResultModel.errorMsg("参数为空或ContentType不规范，请设置：application/json").toString()+"\n");
			return ResultModel.errorMsg("参数为空或ContentType不规范，请设置：application/json");
		}
		logger.error("异常响应信息："+ResultModel.errorMsg(e.getMessage()).toString()+"99999\n");
		return ResultModel.errorMsg(e.getMessage());
	}
}
